# -*- coding: UTF-8 -*-
# __author__ = 'Sengo'
from settings import BASE_DIR, FILE_NAME, ROTATE_AXIS1, ROTATE_AXIS2
import numpy as np


def read_two_file(x, y, z, angle):
    v1, lines1 = read_data(rotate_angle=angle, axis=ROTATE_AXIS1)
    v2, lines2 = read_data(rotate_angle=angle, axis=ROTATE_AXIS2)
    # 拷贝数据 作为第二个图
    vertexes_num = len(v2)

    # 第二个图的各个点在原图的基础上偏移x,y,z坐标
    v2 = np.mat(v2)
    offset = [x, y, z]
    for i in range(vertexes_num):
        v2[i] = v2[i] + offset
    v2 = v2.tolist()

    # 第二个图的线对应的点的索引加上第一个图点的总数
    for i in range(len(lines2)):
        lines2[i] = [x+vertexes_num for x in lines2[i]]

    # 把第二个图的点和线和第一张图的加到一起
    return v1+v2, lines1+lines2


def read_data(path=None, rotate_angle=None, axis=None):
    matric = None
    if rotate_angle:
        matric = create_matric(rotate_angle, axis)
    if not path:
        path = BASE_DIR + "/data/txt/%s.d.txt" % FILE_NAME
    _sum = []
    vertexes = []
    lines = []
    _first_line = 1
    _vertex_line = 0
    with open(path) as f:
        for data in f.readlines():
            data = data.strip('\n')
            # nums for one line
            nums = data.split(" ")
            # read fist line
            if _first_line:
                for re in nums:
                    if re:
                        _sum.append(re)
                _first_line = 0
                continue
            _vertex_line = int(_sum[1])

    # read vertexes and lines
    with open(path) as f:
        i = 1
        for data in f.readlines():
            data = data.strip('\n')
            nums = data.split(" ")
            if i:
                i = 0
                continue
            if _vertex_line:
                _vertex = []
                for re in nums:
                    if re:
                        _vertex.append(float(re))
                # 旋转矩阵
                if matric is not None:
                    _vertex = np.dot(matric, np.mat(_vertex).T).T.tolist()[0]
                vertexes.append(_vertex)
                _vertex_line -= 1
                continue

            # lines
            _line = []
            for re in nums:
                if re:
                    _line.append(int(re)-1)
            lines.append(_line[1:])
    # print _sum
    # print vertexes
    # print lines
    return vertexes, lines


def create_matric(k, axis):
    x = axis[0]
    y = axis[1]
    z = axis[2]
    angle = np.pi / 180 * k
    c = np.cos(angle)
    s = np.sin(angle)
    m = 1 - c
    matric = np.mat(list([[x * x * m + c, x * y * m + z * s, x * z * m - y * s],
                          [y * x * m - z * s, y * y * m + c, y * z * m + x * s],
                          [x * z * m + y * s, y * z * m - x * s, z * z * m + c]]))
    return matric


if __name__ == '__main__':
    P = [-5.53777e-08, 1, 2.87212e-08]
